from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError, ConfigurationError

class MongoDB:
    def __init__(self, uri, db_name):
        self.uri = uri
        self.db_name = db_name
        self.client = None
        self.db = None

    def connect(self):
        try:
            # 连接到 MongoDB
            self.client = MongoClient(self.uri, serverSelectionTimeoutMS=5000)  # 设置超时时间
            # 选择数据库
            self.db = self.client[self.db_name]
            # 尝试直接执行一个操作以测试连接
            self.db.command('ping')  # 通过 ping 测试连接
            print(f"成功连接到 MongoDB 数据库: {self.db_name}")
        except ServerSelectionTimeoutError:
            print("无法连接到 MongoDB，检查 MongoDB 是否在运行以及连接字符串是否正确。")
        except ConfigurationError as e:
            print(f"配置错误: {e}")
        except Exception as e:
            print(f"发生错误: {e}")

    def close(self):
        if self.client:
            self.client.close()
            print("已关闭 MongoDB 连接。")

    def get_collection(self, collection_name):
        if self.db is not None:
            return self.db[collection_name]
        else:
            raise Exception("数据库连接未建立，请先连接到 MongoDB。")

    def insert_one(self, collection_name, document):
        collection = self.get_collection(collection_name)
        result = collection.insert_one(document)
        print(f"插入的文档 ID: {result.inserted_id}")
        return result.inserted_id

    def insert_many(self, collection_name, documents):
        collection = self.get_collection(collection_name)
        result = collection.insert_many(documents)
        print(f"插入的文档 IDs: {result.inserted_ids}")
        return result.inserted_ids


    def find_one_by_field(self, collection_name, field_name, value):
        collection = self.get_collection(collection_name)
        query = {field_name: value}
        document = collection.find_one(query)
        print(f"根据字段 '{field_name}' 查找到的文档: {document}")
        return document

    def find_many_by_field(self, collection_name, field_name, value):
        collection = self.get_collection(collection_name)
        query = {field_name: value}
        documents = list(collection.find(query))
        print(f"根据字段 '{field_name}' 查找到的文档数量: {len(documents)}")
        return documents
    def update_one_by_field(self, collection_name, field_name, value, update_document):
        collection = self.get_collection(collection_name)
        query = {field_name: value}
        result = collection.update_one(query, {"$set": update_document})
        print(f"根据字段 '{field_name}' 更新的文档数量: {result.modified_count}")
        return result.modified_count
    def update_many_by_field(self, collection_name, field_name, value, update_document):
        collection = self.get_collection(collection_name)
        query = {field_name: value}
        result = collection.update_many(query, {"$set": update_document})
        print(f"根据字段 '{field_name}' 更新的文档数量: {result.modified_count}")
        return result.modified_count

    def delete_one_by_field(self, collection_name, field_name, value):
        collection = self.get_collection(collection_name)
        query = {field_name: value}
        result = collection.delete_one(query)
        print(f"根据字段 '{field_name}' 删除的文档数量: {result.deleted_count}")
        return result.deleted_count

    def delete_many_by_field(self, collection_name, field_name, value): 
        collection = self.get_collection(collection_name)
        query = {field_name: value}
        result = collection.delete_many(query)
        print(f"根据字段 '{field_name}' 删除的文档数量: {result.deleted_count}")
        return result.deleted_count